package com.sanshow.charging.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.sanshow.charging.MainActivity;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * @author LiHaiyuan
 * @Description: APP静默安装
 * @date :2018/3/25 20:28
 * @Email :lihaiyuan@tuandai.com
 */
public class SilenceInstallManger {
    private static SilenceInstallManger mInstance;
    private static final String TAG = "Silence";

    public SilenceInstallManger() {
    }

    public static synchronized SilenceInstallManger getInstance() {
        if (mInstance == null) {
            mInstance = new SilenceInstallManger();
        }
        return mInstance;
    }

    /**
     * 开始安装
     *
     * @param context
     * @param apkPath apk本地存储路径
     * @return
     */
    public boolean slientInstall(Context context, String apkPath) {
        File file = new File(apkPath);
        boolean result = false;
        Process process = null;
        OutputStream out = null;
        Log.i(TAG, "file.getPath()：" + file.getPath());
        if (file.exists()) {
            System.out.println(file.getPath() + "==");
            try {
                //if (iSilenceInstall != null) {
                //    iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationStart, "安装开始！");
               // }
                process = Runtime.getRuntime().exec("su");
                out = process.getOutputStream();
                DataOutputStream dataOutputStream = new DataOutputStream(out);
                // 获取文件所有权限
                dataOutputStream.writeBytes("chmod 777 " + file.getPath()
                        + "\n");
                // 进行静默安装命令
                dataOutputStream
                        .writeBytes("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install -r "
                                + file.getPath());
                dataOutputStream.flush();
                // 关闭流操作
                dataOutputStream.close();
                out.close();
                int value = process.waitFor();

                // 代表成功
                if (value == 0) {
                    Toast.makeText(context,"安装成功！",Toast.LENGTH_LONG).show();
                    Log.i(TAG, "安装成功！");
                   // if (iSilenceInstall != null) {
                   //     iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationSuccess, "安装成功！");
                   // }
                    result = true;
                    // 失败
                } else if (value == 1) {
                    Toast.makeText(context,"安装失败！",Toast.LENGTH_LONG).show();
                    Log.i(TAG, "安装失败！");
                    //if (iSilenceInstall != null) {
                   //     iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationFailure, "安装失败！");
                   // }
                    // 未知情况
                } else {
                    Toast.makeText(context,"未知情况！",Toast.LENGTH_LONG).show();
                    //if (iSilenceInstall != null) {
                    //    iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationOther, "未知情况！");
                   // }
                }
            } catch (IOException | InterruptedException e) {
                Log.getStackTraceString(e);
               // if (iSilenceInstall != null) {
                //    String message = "Message:" + e.getMessage();
                //    iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationFailure, message);
               // }
            }
            if (!result) {
                Log.i(TAG, "root权限获取失败，将进行普通安装");
                //if (iSilenceInstall != null) {
                //    iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationFailure,
                //            "root权限获取失败，将进行普通安装");
               // }
                normalInstall(context, apkPath);
                result = true;
            }else{
                startApp(context);
            }
        } else {
            //if (iSilenceInstall != null) {
            //    iSilenceInstall.onDownloadCompleted(SilenceInstallType.installationFailure, "no file.getPath()：" + file.getPath());
            //}
            Log.i(TAG, "no file.getPath()：" + file.getPath());
        }
        return result;
    }

    /**
     * 传统安装
     *
     * @param context
     */
    private void normalInstall(Context context, String apkPath) {
        File file = new File(apkPath);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
        startApp(context);
    }

    /**
     * 安装后自启动apk
     *
     * @param context
     */
    private static void startApp(Context context) {

        Log.e(TAG, "重启APP===");
        Log.e(TAG, "重启APP===");
        AppUtils.relaunchApp();
        Log.e(TAG, "重启APP--->");
        Log.e(TAG, "重启APP--->");

        // am start -S
        /*execRootShellCmd("am start -S  " + context.getPackageName() + "/"
                + MainActivity.class.getCanonicalName() + " \n");*/

        //execRootShellCmd("sleep 10; am start -n " + "com.sanshow.charging/com.sanshow.charging.MainActivity");

    }

    /**
     * 执行shell命令
     *
     * @param cmds
     * @return
     */
    private static boolean execRootShellCmd(String... cmds) {
        if (cmds == null || cmds.length == 0) {
            return false;
        }
        DataOutputStream dos = null;
        InputStream dis = null;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
            dos = new DataOutputStream(p.getOutputStream());

            for (int i = 0; i < cmds.length; i++) {
                dos.writeBytes(cmds[i] + " \n");
            }
            dos.writeBytes("exit \n");

            int code = p.waitFor();

            return code == 0;
        } catch (Exception e) {
            Log.getStackTraceString(e);
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                Log.getStackTraceString(e);
            }
            try {
                if (dis != null) {
                    dis.close();
                }
            } catch (Exception e2) {
                Log.getStackTraceString(e2);
            }
            try {
                if (p != null) {
                    p.destroy();
                    p = null;
                }
            } catch (Exception e3) {
                Log.getStackTraceString(e3);
            }
        }
        return false;
    }
}
